<template>
    <div class="org-tree-wrapper">
        <div class="action-wrapper">
            <div class="search-input">
                <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search" />
            </div>
        </div>
        <el-scrollbar class="tree-scrollbar" :native="false">
            <el-tree :data="deptOptions" :props="{ label: 'name', children: 'children' }"
                :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current default-expand-all
                @node-click="handleNodeClick" :expand-on-click-node="false">
                <template #default="{ node, data }">
                    <div class="icon-name">
                        <IconPlus v-if="orgIconMap[data.type]" :name="orgIconMap[data.type]" />
                        <span>{{ data.name }}</span>
                    </div>
                </template>
            </el-tree>
        </el-scrollbar>
    </div>
</template>

<script setup>
import { treeDeptList } from "@/api/system/dept";
import { GLOBAL_DICTS } from "@/utils/dict"


const deptTreeRef = ref();
const currentOrg = ref();
const deptName = ref();
const deptOptions = ref([]);

const emits = defineEmits(["orgChange"])

const orgIconMap = Object.fromEntries(
    GLOBAL_DICTS.ORG_TYPE.map(item => [item.value, item.icon])
);

/** 查询部门下拉树结构 */
function getDeptTree() {
    let treeParams = { isActive: true }
    return treeDeptList(treeParams).then(response => {
        deptOptions.value = response;
        return response;
    }).finally(res => {
    });
};

watch(deptName, (val) => {
    deptTreeRef.value.filter(val)
})


/** 通过条件过滤节点  */
const filterNode = (value, data) => {
    if (!value) return true;
    return data.name.includes(value);
};

/** 节点单击事件 */
const handleNodeClick = (data) => {
    if (!currentOrg.value || currentOrg.value.id !== data.id) {
        currentOrg.value = data;
        emits("orgChange", data);
    }
};

/** 刷新树结构 */
const handleRefresh = () => {
    getDeptTree();
}


/** 初始化组织机构树 */
const initOrgTree = () => {
    getDeptTree().then(res => {
        nextTick(() => {
            if (deptOptions.value.length > 0) {
                const firstNode = deptTreeRef.value.getNode(deptOptions.value[0])
                deptTreeRef.value.setCurrentKey(firstNode.key)
                handleNodeClick(firstNode.data) // 手动触发节点点击
            }
        })
    })
}


defineExpose({
    refresh: handleRefresh,
})

onMounted(initOrgTree)
</script>

<style lang="scss" scoped>
.org-tree-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column
}

.action-wrapper {
    display: flex;
    margin-bottom: 20px;
    gap: 10px;
    align-items: center;

    .search-input {
        flex: 1;
    }
}

.tree-scrollbar {
    flex: 1;
}
</style>